package com.springboot.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.springboot.utils.JwtUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object>  login(String username){
        Map<String, Object> map = new HashMap<>();
        if(!username.equals("admin")){
            map.put("msg","用户不存在" );
            map.put("code",400 );
            return map;
        }
        Map<String, String> payload = new HashMap<>();
        payload.put("userId","1001" );
        payload.put("username",username );
        String token = JwtUtils.getToken(payload);
        map.put("token",token );
        map.put("msg","请求成功" );
        map.put("code",200 );
        return map;

    }

    @GetMapping("/getUser")
    @ResponseBody
    public Map<String, Object>  getUser(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        try {
            DecodedJWT verify = JwtUtils.verify(request.getHeader("token"));
            map.put("userId",verify.getClaim("userId").asString() );
            map.put("username",verify.getClaim("username").asString() );
            map.put("msg","请求成功" );
            map.put("code",200 );
        } catch (Exception e) {
            map.put("msg","token失效" );
            map.put("code",400 );
        }
        return map;

    }

    /**
     * 拦截器传入
     */
    @GetMapping("/getUserTest")
    @ResponseBody
    public Map<String, Object>  getUserTest(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        map.put("userId", request.getAttribute("userId"));
        map.put("username", request.getAttribute("username"));
        return map;
    }


}
